<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目类型" prop="choiceCategory">
        <el-select v-model="queryParams.choiceCategory" placeholder="请选择选择题目类型" clearable>
          <el-option v-for="dict in dict.type.qbms_choice_category" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目题型" prop="choiceType">
        <el-select v-model="queryParams.choiceType" placeholder="请选择选择题目题型" clearable>
          <el-option v-for="dict in dict.type.qbms_choice_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="科目名称" prop="subjectName">
        <el-input v-model="queryParams.subjectName" placeholder="请输入科目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="章节名称" prop="chapterName">
        <el-input v-model="queryParams.chapterName" placeholder="请输入章节名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="数据状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择数据状态" clearable>
          <el-option v-for="dict in dict.type.common_data_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['qbms:qbmsQuestionChoice:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['qbms:qbmsQuestionChoice:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['qbms:qbmsQuestionChoice:remove']">删除</el-button>
      </el-col>
      <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qbmsQuestionChoiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="所属章节" align="center" prop="chapterName" width="280">
        <template slot-scope="scope">
          {{scope.row.categoryName}} / {{scope.row.subjectName}} /
          <p>
            {{scope.row.chapterName}}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="题干" align="center" prop="stem" width="400" />
      <el-table-column label="选择题类型" align="center" prop="choiceCategory">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qbms_choice_category" :value="scope.row.choiceCategory" />
        </template>
      </el-table-column>
      <el-table-column label="选择题题型" align="center" prop="choiceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qbms_choice_type" :value="scope.row.choiceType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="题目等级" align="center" prop="issueGrade" /> -->
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="数据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['qbms:qbmsQuestionChoice:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['qbms:qbmsQuestionChoice:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改题库选择题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属章节" prop="chapterId">
              <el-cascader v-model="form.chapterId" placeholder="请选择所属章节" :options="qbmsChapterTreeselect" filterable :props="{ value: 'id'}" :show-all-levels="false" @change="chapterChange"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题目类型" prop="choiceCategory">
              <el-select v-model="form.choiceCategory" placeholder="请选择题目类型" @change="choiceCategoryChange">
                <el-option v-for="dict in dict.type.qbms_choice_category" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题目题型" prop="choiceType">
              <el-select v-model="form.choiceType" placeholder="请选择选题目题型">
                <el-option v-for="dict in dict.type.qbms_choice_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="难度等级" prop="issueGrade">
              <el-input-number v-model="form.issueGrade" :min="0" :max="5" label="请输入题目等级"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题目排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" label="请输入题目等级"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题目状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.common_data_status" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="题干" prop="stem">
          <el-input v-model="form.stem" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">题目信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddQbmsQuestionChoiceIssue">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteQbmsQuestionChoiceIssue">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="qbmsQuestionChoiceIssueList" :row-class-name="rowQbmsQuestionChoiceIssueIndex" @selection-change="handleQbmsQuestionChoiceIssueSelectionChange" ref="qbmsQuestionChoiceIssue">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="问题" align="center" prop="issue" />
          <el-table-column label="选项" align="center" prop="issueOptions" />
          <el-table-column label="答案" align="center" prop="answer" width="60">

          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateIssue(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改题库选择题问题对话框 -->
    <el-dialog :title="titleIssue" :visible.sync="openIssue" width="800px" append-to-body>
      <el-form ref="issueForm" :model="issueForm" :rules="rulesIssue" label-width="80px">
        <el-form-item label="问题" prop="issue">
          <el-input v-model="issueForm.issue" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span="20">
            <el-form-item label="题目选项" prop="issueOptions">
              <el-row>
                <el-col :span="12" v-for="(item, index) in issueOptionsList" :key="index">
                  <el-input v-model="issueOptionsList[index]" placeholder="请输入内容">
                    <template slot="prepend">
                      <el-row type="flex">
                        选项
                        <dict-tag :options="dict.type.qbms_choice_answer_options" :value="index + 1" />
                      </el-row>
                    </template>
                  </el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-row>
              <el-button type="primary" @click="addIssueOptionsList()" icon="el-icon-plus">选项</el-button>
            </el-row>
            <el-row>
              <el-button type="info" @click="delIssueOptionsList()" icon="el-icon-minus">选项</el-button>
            </el-row>
          </el-col>
        </el-row>
        <el-form-item label="题目答案" prop="answer">
          <el-checkbox-group v-model="issueAnswerList">
            <el-checkbox v-for="(item, index) in issueOptionsList" :key="index" :label="index + 1 + ''">
              <el-row type="flex">
                选项
                <dict-tag :options="dict.type.qbms_choice_answer_options" :value="index + 1" />
              </el-row>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="答案解释" prop="answerExplain">
          <editor v-model="issueForm.answerExplain" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormIssue">确 定</el-button>
        <el-button @click="cancelIssue">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 题库导入对话框 -->
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?categoryId=' + upload.categoryId" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" slot="tip">
          请选择分类：<el-cascader v-model="upload.categoryId" placeholder="请选择分类" :options="qbmsCategoryTreeselect" filterable :props="{ value: 'id'}" :show-all-levels="false" @change="categoryChange"></el-cascader>

          <!-- <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link> -->
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQbmsQuestionChoice, getQbmsQuestionChoice, delQbmsQuestionChoice, addQbmsQuestionChoice, updateQbmsQuestionChoice } from "@/api/qbms/qbmsQuestionChoice";
import { treeselectQbmsChapter, getQbmsChapter } from "@/api/qbms/qbmsChapter"
import { getToken } from "@/utils/auth";
import { treeselectQbmsCategory, getQbmsCategory } from "@/api/qbms/qbmsCategory";

export default {
  name: "QbmsQuestionChoice",
  dicts: ['qbms_choice_category', 'common_data_status', 'qbms_choice_type', 'qbms_choice_answer_options'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedQbmsQuestionChoiceIssue: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题库选择题表格数据
      qbmsQuestionChoiceList: [],
      // 题库选择题问题表格数据
      qbmsQuestionChoiceIssueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        categoryId: null,
        subjectId: null,
        chapterId: null,
        stem: null,
        choiceCategory: null,
        choiceType: null,
        issueGrade: null,
        sort: null,
        categoryName: null,
        subjectName: null,
        chapterName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        chapterId: [
          { required: true, message: "请选择所属章节", trigger: "blur" }
        ],
        choiceCategory: [
          { required: true, message: "请选择题目类型", trigger: "blur" }
        ],
        issue: [
          { required: true, message: "请输入问题", trigger: "blur" }
        ],
      },

      qbmsChapterTreeselect: [],
      rulesIssue: {
        issue: [
          { required: true, message: "请输入问题", trigger: "blur" }
        ],
      },

      issueForm: {}, // 问题表单
      openIssue: false,
      titleIssue: "",
      issueOptionsList: ["", "", "", ""], // 选项列表
      issueAnswerList: [], // 答案列表
      isEditIssue: false, // 是否为修改
      qbmsCategoryTreeselect: [], // 分类
      // 题库导入参数
      upload: {
        // 是否显示弹出层（题库导入）
        open: false,
        // 弹出层标题（题库导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        categoryId: 0, // 分类ID
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/qbms/qbmsQuestionChoice/importData"
      },

    };
  },
  created() {
    this.getList();
    this.getQbmsChapterTreeselect();
    this.getQbmsCategoryTreeselect();
  },
  methods: {




    /** 添加选项列表 */
    addIssueOptionsList() {
      this.issueOptionsList.push("");
    },

    /** 减少选项列表 */
    delIssueOptionsList() {
      this.issueOptionsList.pop();
    },


    /** 获取章节选项 */
    getQbmsChapterTreeselect() {
      treeselectQbmsChapter().then(res => {
        this.qbmsChapterTreeselect = res.data;
      })
    },

    /** 章节改变 */
    chapterChange(data) {
      getQbmsChapter(data[2]).then(res => {
        let chapter = res.data;
        this.form.categoryId = chapter.categoryId;
        this.form.categoryName = chapter.categoryName;
        this.form.subjectId = chapter.subjectId;
        this.form.subjectName = chapter.subjectName;
        this.form.chapterId = chapter.id;
        this.form.chapterName = chapter.name;
      })
    },

    // 选择题题目类型改变
    choiceCategoryChange(choiceCategory) {
      console.log(choiceCategory);
      if (choiceCategory == 11) { // 单选题

      }
    },


    /** 查询题库选择题列表 */
    getList() {
      this.loading = true;
      listQbmsQuestionChoice(this.queryParams).then(response => {
        this.qbmsQuestionChoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        deptId: null,
        categoryId: null,
        subjectId: null,
        chapterId: null,
        stem: null,
        choiceCategory: null,
        choiceType: null,
        issueGrade: null,
        sort: null,
        categoryName: null,
        subjectName: null,
        chapterName: null,
        delFlag: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.qbmsQuestionChoiceIssueList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /*** 处理问题修改 */
    handleUpdateIssue(row) {
      this.resetIssue;
      this.issueForm = row;
      this.issueOptionsList = row.issueOptions.split("====");
      this.issueAnswerList = row.answer.split(",");
      this.openIssue = true;
      this.titleIssue = "修改题目信息";
      this.isEditIssue = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQbmsQuestionChoice(id).then(response => {
        this.form = response.data;
        this.qbmsQuestionChoiceIssueList = response.data.qbmsQuestionChoiceIssueList;
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.qbmsQuestionChoiceIssueList = this.qbmsQuestionChoiceIssueList;
          if (this.form.id != null) {
            updateQbmsQuestionChoice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQbmsQuestionChoice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除题目编号为"' + ids + '"的数据项？').then(function () {
        return delQbmsQuestionChoice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 题库选择题问题序号 */
    rowQbmsQuestionChoiceIssueIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 题库选择题问题添加按钮操作 */
    handleAddQbmsQuestionChoiceIssue() {
      this.resetIssue();
      this.openIssue = true;
      this.isEditIssue = false;
      this.titleIssue = "添加问题信息";
    },

    // 提交题目信息表单
    submitFormIssue() {
      let issueForm = this.issueForm;

      if (this.isEditIssue) {
        issueForm.issueOptions = this.issueOptionsList.join("====");
        issueForm.answer = this.issueAnswerList.join(",");
      } else {
        let obj = {};
        obj.id = issueForm.id;
        obj.questionId = issueForm.questionId;
        obj.issue = issueForm.issue;
        obj.issueImg = "";
        obj.issueOptions = this.issueOptionsList.join("====");
        obj.answer = this.issueAnswerList.join(",");
        obj.answerExplain = issueForm.answerExplain;
        this.qbmsQuestionChoiceIssueList.push(obj);
      }
      this.openIssue = false;
    },

    // 表单重置
    resetIssue() {
      this.issueForm = {
        id: null,
        questionId: null,
        issue: null,
        issueImg: null,
        issueOptions: null,
        answer: null,
        answerExplain: null,
        answerImg: null,
        issueGrade: null,
        sort: null
      };
      this.issueOptionsList =  ["", "", "", ""]; // 选项列表
      this.issueAnswerList = []; // 答案列表
      this.resetForm("issueForm");
    },

    cancelIssue() {
      this.openIssue = false;
    },

    /** 题库选择题问题删除按钮操作 */
    handleDeleteQbmsQuestionChoiceIssue() {
      if (this.checkedQbmsQuestionChoiceIssue.length == 0) {
        this.$modal.msgError("请先选择要删除的题库选择题问题数据");
      } else {
        const qbmsQuestionChoiceIssueList = this.qbmsQuestionChoiceIssueList;
        const checkedQbmsQuestionChoiceIssue = this.checkedQbmsQuestionChoiceIssue;
        this.qbmsQuestionChoiceIssueList = qbmsQuestionChoiceIssueList.filter(function (item) {
          return checkedQbmsQuestionChoiceIssue.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleQbmsQuestionChoiceIssueSelectionChange(selection) {
      this.checkedQbmsQuestionChoiceIssue = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('qbms/qbmsQuestionChoice/export', {
        ...this.queryParams
      }, `qbmsQuestionChoice_${new Date().getTime()}.xlsx`)
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('qbms/qbmsQuestionChoice/importTemplate', {
      }, `question_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.upload.categoryId) {
        this.$modal.msgError("请选择分类");
        return;
      }
      this.$refs.upload.submit();
    },

    /** 查询题库类别下拉树结构 */
    getQbmsCategoryTreeselect() {
      treeselectQbmsCategory().then(response => {
        this.qbmsCategoryTreeselect = response.data;
      });
    },

    /** 分类改变 */
    categoryChange(data) {
      let categoryId = data[1];
      this.upload.categoryId = categoryId;

    },
  }
};
</script>
